package engine.render;

import engine.scene.Camera3D;
import java.io.File;
import java.util.HashMap;
import math.matrix.mat4f;

public class ShaderEngine
{
    
    private static final String FILE_PATH = "shaders/";
    
    
    private HashMap<String, Shader> shaderMap;
    
    private Shader shader;
    //<editor-fold defaultstate="collapsed" desc="setShaderTo">
    public void setShaderTo(String shaderName)
    {
        this.shader = this.shaderMap.get(shaderName);
        this.shader.bind();
    }
    //</editor-fold>
    
    public ShaderEngine()
    {
        this.shaderMap = new HashMap<>();
        this.loadShaders();
        this.shader = null;
    }
    
    public void bindCamera(Camera3D camera)
    {
        this.shader.bindUniform(
            "u_matrices.proj", 
            camera.getViewMatrices().getMatrixProj().getBuffer()
        );
        this.shader.bindUniform(
            "u_matrices.view", 
            camera.getViewMatrices().getMatrixView().getBuffer()
        );
    }
    
    public void bindMatrixModel(mat4f matrix)
    {
        this.shader.bindUniform("u_matrices.model", matrix.getBuffer());
    }
    
    public void bindTextureUnitMapping()
    {
        this.shader.bindUniform("u_textures.color", Texture.TEX_TYPE_COLOR);
        this.shader.bindUniform("u_textures.normal", Texture.TEX_TYPE_NORMAL);
        this.shader.bindUniform("u_textures.shadow", Texture.TEX_TYPE_SHADOW);
    }
    
    
    private void loadShaders()
    {
        String[] files = new File(ShaderEngine.FILE_PATH).list();
        for (int i = 0; i < files.length; i++)
        {
            if (files[i].endsWith(".vert"))
            {
                int indexOfPeriod = files[i].indexOf(".");
                String fileName = files[i].substring(0, indexOfPeriod);
                Shader shaderFile = new Shader(fileName);
                this.shaderMap.put(fileName, shaderFile);
            }
        }
    }
    
    public void destroy()
    {
        this.shader.unbind();
        this.shader = null;
    }
    
}
